/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.*;
import java.math.*;
import java.text.SimpleDateFormat;

/**
 *
 * @author computer
 */
public class NewAcct extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    String usrName, pwd1, pwd2, pwdHash, DBhash, email, date;
    int dateTemp, tempUID;
    Date now = new Date();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException, Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            usrName = request.getParameter("username");
            pwd1 = request.getParameter("pwd1");
            pwd2 = request.getParameter("pwd2");
            email = request.getParameter("email");



            
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Threadr || Creating Account...</title>");
            out.println("</head>");
            out.println("<body>");

            if(pwd1.equals(pwd2))
            {
                Connect.init();
                Connection conn = Connect.getConnection();
                try
                {
                   Statement stat = conn.createStatement();
                   Statement stat2 = conn.createStatement();
                   Statement stat3 = conn.createStatement();
                   Statement stat4 = conn.createStatement();
                   ResultSet result = stat.executeQuery("SELECT * FROM t_Users WHERE username = '"+usrName+"'");
                   while(result.next())
                   {
                       DBhash = result.getString("pwdHash");
                       if(!DBhash.equals(null))
                       {
                           out.println("Username in use. <br/>");
                           out.println("</body>");
                           out.println("</html>");
                       }
                   }
                   result = stat4.executeQuery("SELECT * FROM t_Users WHERE email = '"+email+"'");
                   while(result.next())
                   {
                       DBhash = result.getString("pwdHash");
                       if(!DBhash.equals(null))
                       {
                           out.println("Email already in use.");
                           out.println("</body>");
                           out.println("</html>");
                       }
                   }

                   now = Calendar.getInstance().getTime();
                   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                   date = formatter.format(now);
                   hash(); //hash the password
                   result = stat2.executeQuery("SELECT UID FROM t_Users");
                   while(result.next())
                   {
                        tempUID = result.getInt("UID");
                   }
                   tempUID++;
                   stat3.executeUpdate("INSERT INTO t_Users VALUES (" + tempUID + ", '" + usrName + "', '" + email + "', '" + pwdHash + "', 0,  '" + date + "', 0, 0, 0)");
                   out.println("Account created.");
                }
                finally
                {
                    conn.close();
                }
            }
            else
            {
                out.println("Passwords do not match. ");
            }
        } finally {
            out.println("<br/><a href=\"index\">Back to homepage</a>");
            out.println("</body>");
            out.println("</html>");
            out.close();
        }
    }

    private void hash() throws Exception{
        MessageDigest m=MessageDigest.getInstance("MD5");
        m.update(pwd1.getBytes(),0,pwd1.length());
        pwdHash = new BigInteger(1,m.digest()).toString(16);
        while (pwdHash.length() < 32) {
            pwdHash = "0" + pwdHash;
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    //@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    //@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Login Servlet";
    }// </editor-fold>
}